import "ol/ol.css";
import {Map, Overlay, View} from "ol";
import {fromLonLat} from "ol/proj";
import {Tile as TitleLayer} from "ol/layer";
import {XYZ} from "ol/source";
import {TDT_URL} from "@/config/map";
import {defaults} from "ol/control";
import startImg from "@/assets/card/start.png";
import midImg from "@/assets/card/mid.png";
import endImg from "@/assets/card/end.png";
import ancientImg from "@/assets/card/ancient_img.png";
import scenic from "@/assets/scenic/scenic.png";
import cun from "@/assets/scenic/cun.png";
import hong from "@/assets/scenic/hong.png";
import {GeoJSON} from "ol/format";
import {Fill, Style} from "ol/style";
import VectorSource from "ol/source/Vector";
import VectorLayer from "ol/layer/Vector";
import {buffer, bbox, toMercator, lineString} from '@turf/turf'
import Stroke from 'ol/style/Stroke';

class OlMap {
  constructor(el) {
    this.map = null;
    this.baseLayer = null;
    this.view = null;
    this.baseLayer = null;
    this.baseLetteringLayer = null;
    this.initMap(el);
    this.antiquityRoadOverlay = null;
    this.antiquityRoadList = [];
    this.antiquityRoadFn = null;
    this.imageLayerType = null;
    this.imgeLayer = [];
    this.imgeLayer25 = [];
    this.antiquityRoadLayerBuffer = null
    this.antiquityRoadLayer = null;
  }

  /**
   * 初始化地圖
   * */
  initMap(el) {
    this.view = new View({
      projection: "EPSG:3857",
      center: fromLonLat([112.925212, 23.713498]),
      zoom: 8,
      minZoom: 6,
      maxZoom: 18,
    });
    this.map = new Map({
      view: this.view,
      target: el, // DOM容器
      controls: defaults({
        zoom: false,
      }),
    });
  }

  /**
   * 创建底图
   * */
  createBaseLayer(url, letteringUrl) {
    if (this.baseLayer || this.baseLetteringLayer) {
      this.map.removeLayer(this.baseLayer);
      this.map.removeLayer(this.baseLetteringLayer);
    }
    this.baseLayer = new TitleLayer({
      source: new XYZ({
        url: url || TDT_URL[0].url,
      }),
      zIndex: 0,
    });
    this.baseLetteringLayer = new TitleLayer({
      source: new XYZ({
        url: letteringUrl || TDT_URL[0].letteringUrl,
      }),
      zIndex: 0,
    });
    this.addLayer(this.baseLayer);
    this.addLayer(this.baseLetteringLayer);
  }

  /**
   * 添加底图
   *  */
  addLayer(layer) {
    this.map.addLayer(layer);
  }

  /**
   * 设置底图中心位置
   */
  setCenter(coo, z) {
    const zoom = z || this.view.getZoom();
    this.view.animate({center: fromLonLat(coo), zoom: zoom});
  }

  /**
   *删除overlay
   */
  removeOverlay(id) {
    const overlayList = this.map.getOverlays().getArray();
    const length = overlayList.length;
    for (let i = length - 1; i >= 0; i--) {
      const currentOveryId = overlayList[i];
      if (id === currentOveryId) {
        this.map.removeOverlay(currentOveryId);
        if (id === "ancient-map") {
          this.antiquityRoadOverlay = null;
        }
      }
    }
  }

  createTooltip(item) {
    const tooltip = document.createElement("div");
    tooltip.className = "overlay-pop-tooltip";
    let imgEl = document.createElement("img");
    imgEl.className = "overlay-pop-ancient-img";
    imgEl.src = ancientImg; // 确保 ancientImg 已经定义
    tooltip.appendChild(imgEl);
    let tooltiptext = document.createElement("span");
    tooltiptext.className = "overlay-pop-tooltiptext";
    tooltiptext.textContent = item.name; // 使用 textContent 代替 innerHTML 更安全
    tooltip.appendChild(tooltiptext);
    return tooltip; // 返回创建的tooltip元素，供后续使用
  }

  /**
   *添加古驿道的OVerly
   *
   */
  addAncientOverlay(list, fn) {
    this.removeOverlay("ancient-map");
    this.antiquityRoadList = list;
    list.forEach((ancientRoadItem) => {
      const nameElement = document.createElement("div");
      const zoom = this.view.getZoom();
      if (zoom > 8) {
        nameElement.className = "overlay-pop-ancient";
        nameElement.textContent = ancientRoadItem.name;
      } else {
        const tooltip = this.createTooltipElement(ancientRoadItem);
        nameElement.appendChild(tooltip);
      }
      if (fn) {
        nameElement.addEventListener("click", fn);
      }
      this.antiquityRoadOverlay = new Overlay({
        position: fromLonLat(ancientRoadItem.coordinates),
        positioning: "center-left",
        element: nameElement,
        id: "ancient-map",
      });
      this.map.addOverlay(this.antiquityRoadOverlay);
    });
  }

  createTooltipElement(ancientRoadItem) {
    const tooltip = document.createElement("div");
    tooltip.className = "overlay-pop-tooltip";
    const imgElement = document.createElement("img");
    imgElement.className = "overlay-pop-ancient-img";
    imgElement.src = ancientImg; // make sure this is defined somewhere
    tooltip.appendChild(imgElement);
    const tooltipText = document.createElement("span");
    tooltipText.className = "overlay-pop-tooltiptext";
    tooltipText.textContent = ancientRoadItem.name;
    tooltip.appendChild(tooltipText);
    return tooltip;
  }

  /**
   * 设置影像图层
   * */
  setImageMaps(data) {
    if (!data.visible) {
      this.setImageLayerOpacity(data.type, null)
      this.imageLayerType = null
      return;
    }
    const isImgLayer25Visible = data.type === 'imgeLayer25' && this.imgeLayer25.length > 0;
    const isImgLayerVisible = data.type === 'imgeLayer' && this.imgeLayer.length > 0;
    if (isImgLayer25Visible) {
      this.setImageLayerOpacity('imgeLayer', false); // 隐藏imgeLayer图层
    } else if (isImgLayerVisible) {
      this.setImageLayerOpacity('imgeLayer25', false); // 隐藏imgeLayer25图层
    }
    this.imageLayerType = data.type;
    const shouldBeVisible = data.type === 'imgeLayer25' ? isImgLayer25Visible : isImgLayerVisible;
    if (shouldBeVisible) {
      this.setImageLayerOpacity(data.type, true); // 根据条件设置图层可见性
    }
    for (let i = 0; i < data.list.length; i++) {
      const item = data.list[i];
      this.createImageLayer(item);
    }

  }

  /**
   * 添加影像图层
   * */
  createImageLayer(data) {
    const zoom = this.view.getZoom()
    const coo1 = fromLonLat([data.latlonbounds[0], data.latlonbounds[1]])
    const coo2 = fromLonLat([data.latlonbounds[2], data.latlonbounds[3]])
    const bounds = [...coo1, ...coo2]
    const imageLayer = new TitleLayer({
      visible: zoom < 14 ? false : true,
      minZoom: data.zooms[0],
      maxZoom: data.zooms[1],
      extent: bounds,
      source: new XYZ({
        url: data.url
      }),
      zIndex: 1
    })
    this.map.addLayer(imageLayer)
    if (this.imageLayerType === 'imgeLayer25') {
      this.imgeLayer25.push(imageLayer);
    }
    if (this.imageLayerType === 'imgeLayer') {
      this.imgeLayer.push(imageLayer)
    }
  }

  /**
   * 设置影像是否可见
   * */
  setImageLayerOpacity(type, opacity) {
    const layerArr = type === 'imgeLayer25' ? this.imgeLayer25 : this.imgeLayer
    if (layerArr && layerArr.length > 0) {
      //查找非空图层设置
      const layerIndex = layerArray.findIndex(item => item);
      if (layerIndex > -1) {
        layerArray[layerIndex].getExtent();
        layerArray[layerIndex].setVisible(opacity);
      }
    }
  }

  /**
   * 古道路线缓冲区
   * */
  renderAntiquityRoadLineBuffer(data) {
    if (this.antiquityRoadLayerBuffer) {
      this.map.removeLayer(this.antiquityRoadLayerBuffer)
    }
    const dataBuffer = buffer(data, 100 / 1000, {units: 'kilometers'});
    const readFeatureBuffer = new GeoJSON().readFeatures(dataBuffer, {
      dataProjection: 'EPSG:4326',
      featureProjection: 'EPSG:3857'
    })
    for (let i = 0; i < readFeatureBuffer.length; i++) {
      const feature = readFeatureBuffer[i]
      feature.set("name", 'antiquity-line-buffer')
    }
    const styleBuffer = [
      new Style({
        fill: new Fill({
          color: 'rgba(228, 197, 190, 0.8)'
        })
      })
    ]
    const vectorSource = new VectorSource({
      features: readFeatureBuffer
    })
    this.antiquityRoadLayerBuffer = new VectorLayer({
      source: vectorSource,
      styleBuffer: styleBuffer,
      zIndex: 100
    })
    this.addLayer(this.antiquityRoadLayerBuffer)
  }

  /**
   *渲染古道路线
   * */
  renderAntiquityRoadLine(data) {
    if (this.antiquityRoadLayer) {
      this.map.removeLayer(this.antiquityRoadLayer)
    }
    const readFeature = new GeoJSON().readFeatures(data, {
      dataProjection: 'EPSG:4326',
      featureProjection: 'EPSG:3857'
    })
    /*获取四至范围*/
    const bboxExtent = bbox(toMercator(data))
    //移动到四至范围
    this.map.getView().fit(bboxExtent)
    const zoom = this.map.getView().getZoom() - 0.3
    this.map.getView().setZoom(zoom)
    for (let i = 0; i < readFeature.length; i++) {
      const feature = readFeature[i]
      //getProperties()获取所有属性名称和值的对象。
      const {color} = feature.getProperties();
      const style = [
        new Style({
          stroke: new Stroke({
            color: color || '#c68171',
            width: 6
          })
        })
      ]
      feature.set('name', 'antiquity-line');
      feature.setStyle(style)
    }
    let vectorSource = new VectorSource({
      features: readFeature
    })
    this.antiquityRoadLayer = new VectorLayer({
      source: vectorSource,
      zIndex: 10
    })
    this.addLayer(this.antiquityRoadLayer)
  }

  /**
   * 添加鼠标移动事件
   * */
  addMouseMoveEvent(fn) {
    this.map.on('pointermove', fn);
  }
  /**
   * 添加鼠标点击事件
   * */
  addMouseClickEvent(fn){
    this.map.on('click', fn);
  }
  /**
   * 销毁事件
   * */
  unMapEvent(type,event){
    this.map.un(type,event)
  }
}

export default OlMap;
